/*
 * SteepTimer - A timer designed for tea fanatics
 * Copyright (C) 2011  Wesley Crossman
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "TeaTimeLineEdit.h"
#include <QRegExpValidator>
#include <QFocusEvent>
#include <QMouseEvent>
#include <QTimer>

QRegExp TeaTimeLineEdit::regExp("(\\d?\\d):(\\d\\d)");

TeaTimeLineEdit::TeaTimeLineEdit(QWidget *parent) : QLineEdit(parent) {
}

QTime TeaTimeLineEdit::getTime() {
    if (regExp.exactMatch(text())) {
        int s = regExp.cap(2).toInt();
        int m = regExp.cap(1).toInt();
        int h = 0;
        if (s > 59) {s -= 60; ++m;}
        if (m > 59) {m -= 60; ++h;}
        if (!h && !m && !s) {
            return QTime();
        } else {
            return QTime(h, m, s);
        }
    } else {
        return QTime();
    }
}

void TeaTimeLineEdit::setTime(const QTime &time) {
    if (time.isValid()) {
        setText(time.toString("mm:ss"));
    } else {
        setText("00:00");
    }
    home(false);
}

void TeaTimeLineEdit::keyPressEvent(QKeyEvent *e) {
    QTime oldTime = getTime();
    QLineEdit::keyPressEvent(e);
    if (oldTime.isNull() != getTime().isNull()) emit validityChanged(!oldTime.isNull());
}
